// packageA/pages/sku/index.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        statusList: [
            { id: 0, name: '全部' },
            { id: 1, name: '上架' },
            { id: 2, name: '下架' }
        ],
        currentStatus: { id: 0, name: '全部' },

        categoryList: [
            { id: 0, name: '全部' }
            // ,
            // { id: 1, name: '推荐' },
            // { id: 2, name: '奶皮子酸奶' },
            // { id: 3, name: '特色口味' },
            // { id: 4, name: '大杯系列' },
            // { id: 5, name: '小杯系列' },
            // { id: 6, name: '新品上市' },
            // { id: 7, name: '优惠套餐' },
            // { id: 8, name: '酸奶饮品' },
            // { id: 9, name: '小吃搭配' }
        ],
        currentCategory: { id: 0, name: '全部' },

        brandList: [
            { id: 0, name: '全部' },
            { id: 1, name: '草原牧场' },
            { id: 2, name: '雪山牦牛' },
            { id: 3, name: '黄金奶源' }
        ],
        currentBrand: { id: 0, name: '全部' },

        goodsList: [
            {
                id: '1001',
                images: [
                    'https://xxg.xjdio.com/images/Zxrh/Product/202510/202512241010184712e676-b296-469a-a817-d638a020f5a6.mp4',
                    'https://xxx.xjdio.com/static/img/3.jpg',
                    'https://xxx.xjdio.com/static/img/1.jpg'
                ],
                name: '奶皮子酸奶（椰子味）',
                subtitle: '椰香浓郁，口感丝滑',
                brand: '草原牧场',
                category: '特色口味',
                price: 28.8,
                memberPrice: 25.9,
                spec: '500g*2盒',
                unit: '杯',
                stock: 156,
                status: 1,
                isRecommend: true,
                isNew: false
            },
            {
                id: '1002',
                images: [
                    'https://xxx.xjdio.com/static/img/2.jpg'
                ],
                name: '奶皮子酸奶（榴莲味）',
                subtitle: '榴莲果肉，双重享受',
                brand: '雪山牦牛',
                category: '特色口味',
                price: 32.8,
                memberPrice: 29.9,
                spec: '500g*2盒',
                unit: '杯',
                stock: 89,
                status: 0,
                isRecommend: false,
                isNew: true
            }
        ]
    },
    //根据是否上架获取sku
    GetSkusByStatusAsync(status) {
        return wx.Http.get("/SkuAppService/Xncf.Xxgmall_SkuAppService.GetSkusByStatusAsync", {
            status
        })
    },
    // 状态筛选
    statusChange(e) {
        const index = e.detail.value;
        const mystatus1 = this.data.statusList[index].name;
        if (mystatus1 == "全部") {
            this.GetAllSkusAsyncAsync().then((res => {
                if (res.data) {
                    this.setData({
                        goodsList: res.data,
                        filteredGoods: res.data,
                        currentStatus: this.data.statusList[index]
                    });
                }
            }))
        } else {
            const mystatus = this.data.statusList[index].name == "上架" ? true : false;
            console.log("是否上架：" + mystatus)
            this.GetSkusByStatusAsync(mystatus).then((res) => {
                this.setData({
                    goodsList: res.data,
                    currentStatus: this.data.statusList[index]
                })
            })
        }


        this.filterGoods()
    },
    // 根据分类ID获取商品
    getProductsByCategory: function (categoryId) {
        return wx.Http.get("/SkuAppService/Xncf.Xxgmall_SkuAppService.GetSkusByCategoryAsync", {
            categoryId
        })
        // return this.data.allProducts.filter(product => product.category === categoryId);
    },
    // 分类筛选
    categoryChange(e) {
        const index = e.detail.value;
        const categoryid = this.data.categoryList[index].id;
        if (categoryid == 0) {
            this.GetAllSkusAsyncAsync().then((res => {
                if (res.data) {
                    this.setData({
                        category_Id: categoryid,
                        currentCategory: this.data.categoryList[index],
                        goodsList: res.data,
                        filteredGoods: res.data
                    });
                }
            }))
        } else {
            this.getProductsByCategory(categoryid).then((res) => {
                this.setData({
                    category_Id: categoryid,
                    currentCategory: this.data.categoryList[index],
                    goodsList: res.data
                })
            })
        }


        this.filterGoods()
    },
    GetSkusByBrandAsync(brand) {
        return wx.Http.get("/SkuAppService/Xncf.Xxgmall_SkuAppService.GetSkusByBrandAsync", {
            brand
        })
    },
    // 品牌筛选
    brandChange(e) {
        const index = e.detail.value
        if (this.data.brandList[index].name == "全部") {
            this.GetAllSkusAsyncAsync().then((res => {
                if (res.data) {
                    this.setData({
                        goodsList: res.data,
                        filteredGoods: res.data,
                        currentBrand: this.data.brandList[index]
                    });
                }
            }))
        } else {
            this.GetSkusByBrandAsync(this.data.brandList[index].name).then((res) => {
                if (res.data) {
                    this.setData({
                        goodsList: res.data,
                        filteredGoods: res.data,
                        currentBrand: this.data.brandList[index]
                    });
                }
            })
        }
        this.filterGoods()
    },

    // 综合筛选
    filterGoods() {
        // 实际开发中这里应该发起网络请求获取筛选后的数据
        console.log('筛选条件:', {
            status: this.data.currentStatus,
            category: this.data.currentCategory,
            brand: this.data.currentBrand
        })
    },

    // 跳转到添加商品页面
    navigateToAdd() {
        wx.navigateTo({
            url: '/packageA/pages/addSku/index'
        })
    },

    // 编辑商品
    editGoods(e) {
        const id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: `/packageA/pages/editSku/index?id=${id}`
        })
    },
    //商品列表
    GetAllSkusAsyncAsync() {
        return wx.Http.post("/SkuAppService/Xncf.Xxgmall_SkuAppService.GetAllSkusAsyncAsync", {
        });
    },
    //更改上架下架
    UpdateSkuStatusAsync(param) {
        return wx.Http.post("/SkuAppService/Xncf.Xxgmall_SkuAppService.UpdateSkuStatusAsync", {
            id: param.id,
            status: param.status
        })
    },
    // 上架/下架
    toggleStatus(e) {
        const id = e.currentTarget.dataset.id;

        wx.showModal({
            title: '提示',
            content: `确定要${this.data.goodsList.find(item => item.id === id).status ? '下架' : '上架'}该商品吗？`,
            success: (res) => {
                if (res.confirm) {
                    const param = {
                        id: e.currentTarget.dataset.id,
                        status: e.currentTarget.dataset.status
                    }
                    this.UpdateSkuStatusAsync(param).then((res => {
                        if (res.data) {
                            // 实际开发中这里应该发起网络请求修改状态
                            const goodsList = this.data.goodsList.map(item => {
                                if (item.id === id) {
                                    item.status = item.status ? 0 : 1
                                }
                                return item
                            })
                            this.setData({ goodsList })
                            wx.showToast({
                                title: '操作成功',
                                icon: 'success'
                            })
                        }
                    }))

                }
            }
        })
    },

    // 删除商品
    deleteGoods(e) {
        const id = e.currentTarget.dataset.id
        wx.showModal({
            title: '提示',
            content: '确定要删除该商品吗？',
            success: (res) => {
                if (res.confirm) {
                    // 实际开发中这里应该发起网络请求删除数据
                    const goodsList = this.data.goodsList.filter(item => item.id !== id)
                    this.setData({ goodsList })
                    wx.showToast({
                        title: '删除成功',
                        icon: 'success'
                    })
                }
            }
        })
    },
    //商品分类
    GetAllCategoriesAsync() {
        return wx.Http.post("/ProductCategoryAppService/Xncf.Xxgmall_ProductCategoryAppService.GetAllCategoriesAsync", {})
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.GetAllCategoriesAsync().then((res) => {
            if (res.data) {
                const mergedArray = this.data.categoryList.concat(res.data);
                this.setData({
                    categoryList: mergedArray,
                    category_Id: res.data[0].id
                })
            }
        })
        this.loadGoodsData();
    },
    loadProducts() {
        wx.request({
            url: 'https://your-api.com/products',
            success: (res) => {
                this.setData({ productList: res.data });
            }
        });
    },
    // 加载商品数据
    loadGoodsData() {
        this.GetAllSkusAsyncAsync().then((res => {
            if (res.data) {
                this.setData({
                    goodsList: res.data,
                    filteredGoods: goods
                });
            }
        }))
        const goods = [
            // 推荐分类的商品
            { id: 1, name: '奶皮子酸奶', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 8.9, quantity: 0, category: 1, description: '经典原味，香浓醇厚' },
            { id: 2, name: '奶皮子酸奶（草莓味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 8.9, quantity: 0, category: 1, description: '新鲜草莓，酸甜可口' },
            { id: 3, name: '奶皮子酸奶（抹茶味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 8.9, quantity: 0, category: 1, description: '日式抹茶，清香回甘' },

            // 奶皮子酸奶分类的商品
            { id: 4, name: '经典奶皮子酸奶', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 8.9, quantity: 0, category: 2, description: '传统工艺，纯正口感' },
            { id: 5, name: '特浓奶皮子酸奶', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 10.9, quantity: 0, category: 2, description: '加倍浓醇，口感丰富' },
            { id: 6, name: '低脂奶皮子酸奶', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 9.9, quantity: 0, category: 2, description: '健康低脂，轻盈无负担' },

            // 特色口味分类的商品
            { id: 7, name: '奶皮子酸奶（红枣味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 8.9, quantity: 0, category: 3, description: '滋补红枣，营养美味' },
            { id: 8, name: '奶皮子酸奶（蓝莓味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 9.9, quantity: 0, category: 3, description: '新鲜蓝莓，果香浓郁' },
            { id: 9, name: '奶皮子酸奶（芒果味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 9.9, quantity: 0, category: 3, description: '热带芒果，香甜爽口' },
            { id: 10, name: '奶皮子酸奶（蜜桃味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 9.9, quantity: 0, category: 3, description: '水蜜桃香，清新怡人' },

            // 大杯系列分类的商品
            { id: 11, name: '奶皮子酸奶（大杯）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 9.9, quantity: 0, category: 4, description: '大容量，更满足' },
            { id: 12, name: '草莓味奶皮子酸奶（大杯）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 10.9, quantity: 0, category: 4, description: '大杯草莓，双倍快乐' },
            { id: 13, name: '抹茶味奶皮子酸奶（大杯）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 10.9, quantity: 0, category: 4, description: '大杯抹茶，清新享受' },

            // 小杯系列分类的商品
            { id: 14, name: '奶皮子酸奶（小杯）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 7.9, quantity: 0, category: 5, description: '小巧精致，刚刚好' },
            { id: 15, name: '草莓味奶皮子酸奶（小杯）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 8.9, quantity: 0, category: 5, description: '小杯草莓，轻享美味' },
            { id: 16, name: '抹茶味奶皮子酸奶（小杯）', price: 8.9, quantity: 0, category: 5, description: '小杯抹茶，清新一刻' },

            // 新品上市分类的商品
            { id: 17, name: '奶皮子酸奶（椰子味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 10.9, quantity: 0, category: 6, description: '新品上市，椰香四溢' },
            { id: 18, name: '奶皮子酸奶（榴莲味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 12.9, quantity: 0, category: 6, description: '新品上市，榴莲爱好者必选' },
            { id: 19, name: '奶皮子酸奶（黑糖味）', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 9.9, quantity: 0, category: 6, description: '新品上市，黑糖香甜' },

            // 优惠套餐分类的商品
            { id: 20, name: '经典双人套餐', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 16.9, quantity: 0, category: 7, description: '原味+草莓味，超值享受' },
            { id: 21, name: '特色三人套餐', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 25.9, quantity: 0, category: 7, description: '原味+草莓+抹茶，多样选择' },
            { id: 22, name: '全家福套餐', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 35.9, quantity: 0, category: 7, description: '四种口味，尽享美味' },

            // 酸奶饮品分类的商品
            { id: 23, name: '酸奶水果捞', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 12.9, quantity: 0, category: 8, description: '新鲜水果+酸奶，健康美味' },
            { id: 24, name: '酸奶冰沙', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 11.9, quantity: 0, category: 8, description: '冰爽口感，夏日必备' },
            { id: 25, name: '酸奶昔', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 13.9, quantity: 0, category: 8, description: '绵密口感，层次丰富' },

            // 小吃搭配分类的商品
            { id: 26, name: '酸奶配麦片', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 6.9, quantity: 0, category: 9, description: '香脆麦片，营养搭配' },
            { id: 27, name: '酸奶配坚果', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 8.9, quantity: 0, category: 9, description: '多种坚果，口感丰富' },
            { id: 28, name: '酸奶配蜂蜜', image: 'https://xxx.xjdio.com/static/img/1.jpg', price: 5.9, quantity: 0, category: 9, description: '天然蜂蜜，甜蜜享受' }
        ];
        this.setData({
            goodsList: goods,
            filteredGoods: goods
        });
    },

    // 搜索处理
    handleSearch(e) {
        const keyword = e.detail.value;
        this.setData({ searchText: keyword });
        this.filterGoods();
    },

    // 排序处理
    handleSort(e) {
        this.setData({ sortIndex: e.detail.value });
        this.filterGoods();
    },

    // 分类处理
    handleCategory(e) {
        this.setData({ categoryIndex: e.detail.value });
        this.filterGoods();
    },

    // 综合筛选方法
    filterGoods() {
        let { goodsList, searchText, sortIndex, categoryIndex } = this.data;
        let result = [...goodsList];

        // 分类筛选
        if (categoryIndex > 0) {
            const category = this.data.categoryOptions[categoryIndex];
            result = result.filter(item => item.category === category);
        }

        // 搜索筛选
        if (searchText) {
            result = result.filter(item => item.name.includes(searchText));
        }

        // 排序处理
        switch (sortIndex) {
            case '1': result.sort((a, b) => a.price - b.price); break;
            case '2': result.sort((a, b) => b.price - a.price); break;
            case '3': result.sort((a, b) => b.sales - a.sales); break;
        }

        this.setData({ filteredGoods: result });
    },

    // 跳转详情页
    goToDetail(e) {
        const id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: `/pages/goods/detail?id=${id}`
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.onLoad();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})